import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    //private List<Message> messageList = new ArrayList<>();
    // 直接使用数据库
    private List<Message> load() throws SQLException {
        // 从数据库中加载/查询数据

        // 1. 先有一个数据源
//        DataSource dataSource = new MysqlDataSource();
//        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/all_demo?characterEncoding=utf8&useSSL=false");
//        ((MysqlDataSource)dataSource).setUser("root");
//        ((MysqlDataSource)dataSource).setPassword("Xianmeng");

        // 单例模式
        DataSource dataSource = DBUtil.getDataSource();

        // 2. 建立连接:java.sql的Connection!!
        Connection connection = dataSource.getConnection();

        // 3. 构造sql语句
        String sql = "select * from message";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 4. 执行SQL语句进行操作
        ResultSet resultSet = statement.executeQuery();

        // 5. 遍历结果集合
        List<Message> messageList = new ArrayList<>();
        while (resultSet.next()) {
            Message message = new Message();
            message.setFrom(resultSet.getString("from"));
            message.setTo(resultSet.getString("to"));
            message.setMessage(resultSet.getString("message"));
            messageList.add(message);
        }

        // 6. 关闭连接
        statement.close();
        connection.close();

        return messageList;
    }

    private void save(Message message) throws SQLException {
        // 保存数据到数据库

        // 1. 先有一个数据源
//        DataSource dataSource = new MysqlDataSource();
//        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/all_demo?characterEncoding=utf8&useSSL=false");
//        ((MysqlDataSource)dataSource).setUser("root");
//        ((MysqlDataSource)dataSource).setPassword("Xianmeng");

        // 其实这重复代码不适合创建多份，更好地做法其实是使用单例模式，把DataSource单独拎出来！
        DataSource dataSource = DBUtil.getDataSource();

        // 2. 建立连接:java.sql的Connection!!
        Connection connection = dataSource.getConnection();

        // 3. 构造sql语句
        String sql = "insert into message values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,message.getFrom());
        statement.setString(2,message.getTo());
        statement.setString(3,message.getMessage());

        // 4. 执行SQL语句进行操作
        int ret = statement.executeUpdate();
        System.out.println("ret=" + ret);

        // 5. 关闭连接
        statement.close();
        connection.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从服务器获取数据
        // 也就是将messageList中的结果返回到浏览器上（转成JSON字符串返回）

        // 显式声明当前的响应数据的格式，不要让客户端去猜！
        resp.setContentType("application/json; charset=utf8");
        //resp.getWriter().write(objectMapper.writeValueAsString(messageList));

        List<Message> messageList = null;
        try {
            messageList = load();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        resp.getWriter().write(objectMapper.writeValueAsString(messageList));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 客户端向服务器提交数据

        // 获取body中的数据并解析
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        // 保存数据message，最简单的方法就是保存到内存中
        // messageList.add(message);

        try {
            save(message);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        // 设置一个响应状态
        resp.setStatus(200);
        // 打印：
        System.out.println("提交数据成功：" + "from=" + message.getFrom() + ",to=" + message.getTo()
        + ", message=" + message.getMessage());
    }
}
